var APIURL = 'http://api-rinkeby.etherscan.io/api';
var APIKEY = 'c1320f9466a44eb892740d0b7033a7c3';
var RPC_URL = 'https://rinkeby.infura.io/v3/' + APIKEY;

var getAPIParam = (modu, action, address, start, end, page, pageSize, sort) => {
		//http://api-rinkeby.etherscan.io/api?module=account&action=txlist&address=${address}&startblock=${start}&endblock=${end}&sort=desc&apikey=${APIKEY}
		return {
				module: modu,
				action: action,
				address: address,
				startblock: start,
				endblock: end,
				page: page,
				offset: pageSize,
				sort: sort,
				apikey: APIKEY
		}
}

var getTxListParam = (address, end, page) => {
		return getAPIParam('account', 'txlist', address, 0, end, page, 10, 'desc');
}

//https://api-rinkeby.etherscan.io/api?module=account&action=tokentx&contractaddress=0x18f72ff4b2049b24b60705f6f59d733438361152&address=0x1aC2F04ea466991bC91C802150a1D2730D2bBB65&page=1&offset=100&sort=asc&apikey=c1320f9466a44eb892740d0b7033a7c3
var getTokenAPIParam = (modu, action, contractaddress, address, page, pageSize, sort) => {
		return {
				module: modu,
				action: action,
				contractaddress: contractaddress,
				address: address,
				page: page,
				offset: pageSize,
				sort: sort,
				apikey: APIKEY
		}
}

var getTokenTxListParam = (contractaddress, address, page) => {
		return getTokenAPIParam('account', 'tokentx', contractaddress, address, page, 10, 'desc');
}


var DEFAULT_ACCOUNT = '0x1aC2F04ea466991bC91C802150a1D2730D2bBB65';
var DEFAULT_ACCOUNT_KEY = '*****';



//var RPC_URL = 'https://mainnet.infura.io/v3/c1320f9466a44eb892740d0b7033a7c3';
//var DEFAULT_ACCOUNT = '0x6B0c930f19d2153CC1f614aEf586047b67674d00';
//var DEFAULT_ACCOUNT_KEY = '0x717e4875b0dbef9d7642c304b881873b2454d7f0e9fd2460c86edf85fc596213';



if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider(RPC_URL));
}


var info = (res) => {
	return `<p class="text-info">${res}</p>`;
}

var errs = (res) => {
	return `<p class="text-danger">${res}</p>`;
}

$('.eth-info').append(info(`节点地址： ${RPC_URL}`));

// 获得区块编号
web3.eth.getBlockNumber().then(num => {
	$('.eth-info').append(info(`最新区块：<a href="https://rinkeby.etherscan.io/block/${num}" target="_blank">${num}</a>`));
});

// 监听状态
// web3.eth.net.isListening().then(ls => {
// 	$('.eth-info').append(info('监听状态： ' + ls));
// });

// 同步状态
// web3.eth.isSyncing().then(ls => {
// 	$('.eth-info').append(info('同步状态： ' + ls));
// });

// 挖矿状态
// web3.eth.isMining().then(ls => {
// 	$('.eth-info').append(info('挖矿状态： ' + ls));
// });


var gasPrices = '';
// 当前gasPrice
web3.eth.getGasPrice().then(gasPrice => {
	gasPrices = web3.utils.fromWei(web3.utils.toWei(gasPrice, 'gwei') * 10 + '');
	console.log('gasPrices: ' + gasPrices);
	$('.eth-info').append(info('当前gasPrice： ' + web3.utils.fromWei(gasPrice, 'ether') + ' ( ' + web3.utils.fromWei(gasPrice, 'gwei') + ' Gwei)'));
});

// 挖矿周期
// web3.eth.getHashrate().then(rs => {
// 	$('.eth-info').append(info(`挖矿速度 (当前矿点每秒hash次数): ${rs}`));
// });

// 协议版本
// web3.eth.getProtocolVersion().then(rs => {
// 	$('.eth-info').append(info(`当前协议版本: ${rs}`));
// });

// 链接节点数量
web3.eth.net.getPeerCount().then(rs => {
	$('.eth-info').append(info(`当前节点连接其他节点数: ${rs}`));
});


$('.local-info').append(info('web3.js 版本： ' + web3.version));


// 主网账户
web3.eth.defaultAccount = DEFAULT_ACCOUNT;
$('.local-info').append(info("默认账户： " + web3.eth.defaultAccount));
$('.local-info').append(info(`账户私钥： ${DEFAULT_ACCOUNT_KEY}`));
$('.local-info').append(info(`测试账户： 0x4e13A733826cB2146735534d8e56602384655393`));
$('.local-info').append(info(`测试账户私钥： ***`));

web3.eth.getBalance(web3.eth.defaultAccount).then(balance => {
	var ebalance = web3.utils.fromWei(balance, 'ether');
	$('.local-info').append(info("账户ETH余额：" + ebalance));
});

web3.eth.getTransactionCount(web3.eth.defaultAccount).then(rs => {
	$('.local-info').append(info(`默认账户交易数量: ${rs}`));
});

var code = $('#sourceCode').val();
var abi = JSON.parse($('#sourceAbi').val());


var getAccount = key => {
		if (key.indexOf('0x') !== 0) {
			  key = '0x' + key;
		}
		if (key.length !== 66) {
			  throw '私钥错误';
		}
		var account = web3.eth.accounts.privateKeyToAccount(key);
		
		return account;
}

var checkNull = (...txt) => {
		for(var i=0, l=txt.length; i<l; i++) {
			  if (txt[i] === '') { throw '参数异常'}
		}
}

var formGroup = (inputLen, names, types) =>{
	var html = '';
	for (var i=0; i<inputLen; i++) {
		html += `<div class="form-group form-inline col-lg-12">
					<label class="control-label col-lg-2 text-right">${names[i] == '' || names[i] == undefined ? types[i] : names[i]}</label>
					<input type="text" class="form-control col-lg-10" name="inputs" data-isfrom="${names[i]=='_from'}" data-type="${types[i]}" placeholder="${types[i]}" />
				</div>`;
	}
	return html;
}

var addPreZero = num => {
	  var t = (num+'').length,
	  		s = '';
	  for(var i=0; i<64-t; i++){
	    	s += '0';
	  }
	  return s+num;
}

var getTxData = (from, to, data, value) => {
		return {
							  gasLimit: web3.utils.toHex(100000),
							  from: from,
							  to: to,
							  data: data,
							  value: value,
							  gasPrice: web3.utils.toWei(gasPrices, 'gwei')
						}
}

var sendTransaction = (txData, privateKey, dom) => {
		var index = layer.load(0, {
			  shade: [0.4, '#fff']
		});

		web3.eth.accounts.signTransaction(txData, privateKey).then(tx => {
				console.log('Result: ', tx);

				web3.eth.sendSignedTransaction(tx.rawTransaction).on('receipt', res => {
						layer.msg('操作成功');
						$(dom).html('操作结果： ' + JSON.stringify(res));
						layer.close(index);
				}).on('error', err => {
						layer.msg('操作异常');
						console.log(err);
						layer.close(index);
				});
		});
}